package com.bacon.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.bacon.gmall.cart.client.CartFeignClient;
import com.bacon.gmall.common.constant.RedisConst;
import com.bacon.gmall.common.result.Result;
import com.bacon.gmall.common.util.AuthContextHolder;
import com.bacon.gmall.model.cart.CartInfo;
import com.bacon.gmall.model.order.OrderDetail;
import com.bacon.gmall.model.order.OrderInfo;
import com.bacon.gmall.model.user.UserAddress;
import com.bacon.gmall.order.service.OrderService;
import com.bacon.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author： bacon、
 * @version： 1.0
 * @create： 2021-01-06 13:14
 * @description:
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {
    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    //获取订单数据
    @GetMapping("/auth/trade")
    public HashMap<String, Object> trade(HttpServletRequest request) {

        HashMap<String, Object> map = new HashMap<>();

        //用户地址集合
        List<UserAddress> userAddressList = userFeignClient.findUserAddressList();
        //选中商品集合
        List<CartInfo> cartListByIsChecked = cartFeignClient.findCartListByIsChecked();

        //商品集合OrderDetail
        List<OrderDetail> detailArrayList = cartListByIsChecked.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            return orderDetail;
        }).collect(Collectors.toList());

        //总商品数量
        long totalNum = detailArrayList.stream().collect(Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();

        //总价格
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderDetail orderDetail : detailArrayList) {
            totalAmount = totalAmount.add(orderDetail.getOrderPrice().multiply(new BigDecimal(orderDetail.getSkuNum())));
        }

        //订单Id
        String tradeNo = UUID.randomUUID().toString();
        String userId = AuthContextHolder.getUserId(request);
        redisTemplate.opsForValue().set(RedisConst.USER_TRADE_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX, tradeNo);

        map.put("tradeNo", tradeNo);
        map.put("userAddressList", userAddressList);
        map.put("detailArrayList", detailArrayList);
        map.put("totalAmount", totalAmount);
        map.put("totalNum", totalNum);

        return map;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(
            String tradeNo,
            @RequestBody OrderInfo orderInfo,
            HttpServletRequest request) {

        //1、判断订单号是否正确或存在
        String userId = AuthContextHolder.getUserId(request);
        String tradeNumber = (String) redisTemplate.opsForValue().
                get(RedisConst.USER_TRADE_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX);

        //redis失效
        //2种情况：1、redis过期 2、非正常途径进入
        if (StringUtils.isEmpty(tradeNumber)) {
            return Result.fail().message("请不要重复提交");
        }

        //用户携带的tradeNo和redis中的信息不一致
        if (!tradeNumber.equals(tradeNo)) {
            return Result.fail().message("非法操作");
        }
        redisTemplate.delete(
                RedisConst.USER_TRADE_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX);
        //2、校验仓库是否有货
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();

        //如果缺货，本次订单失效
        for (OrderDetail orderDetail : orderDetailList) {
            Boolean isHasStock = orderService.hasStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
            if (!isHasStock) {
                return Result.fail().message(orderDetail.getSkuName() + " : 无货");
            }
        }
        //3、提交订单
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderService.submitOrder(orderInfo);
        return Result.ok(orderId);
    }

    //根据Id 获取订单
    @GetMapping("auth/getOrderById/{orderId}")
    public OrderInfo getOrderById(@PathVariable Long orderId){
        return orderService.getOrderById(orderId);
    }

    @PostMapping("/orderSplit")
    public String orderSplit(Long orderId , String wareSkuMap){

        List<OrderInfo> list = orderService.orderSplit(orderId,wareSkuMap);

        List<Map> collect = list.stream().map(orderInfo -> {
            return orderService.initWareOrder(orderInfo.getId());
        }).collect(Collectors.toList());

        return JSONObject.toJSONString(collect);
    }
}
